package com.travel.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.travel.entity.Hotel;
import com.travel.entity.Room;
import com.travel.entity.RoomType;
import com.travel.service.RoomService;
import com.travel.service.impl.HotelServiceImpl;
import com.travel.service.impl.RoomServiceImpl;
import com.travel.service.impl.RoomTypeServiceImpl;
import com.travel.util.PageInfo;

/**
 * Servlet implementation class HotelController
 */
@WebServlet("/RoomServlet")
@MultipartConfig // 表示该控制器支持文件上传
public class RoomServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
     
	// 引入RoomService
	private RoomService roomService = new RoomServiceImpl();
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RoomServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			
		// 控制器如何获取请求携带的参数?
		String op = request.getParameter("op");	
		if ("searchRoomByPage".equals(op)) {
			// 查询列表
			try {
				doSearchRoomByPageAndName(request, response);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if ("deleteRoomById".equals(op)) {
			try {
				doDeleteRoomById(request, response);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else if ("getRoomById".equals(op)) {
			try {
				doGetRoomById(request, response);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}  else if("modify".equals(op)) {
			// 修改
			doModify(request, response);
		} else if("initSelct".equals(op)) {
			// 初始化房间类型选择框的方法
			doInitSelect(request, response);
		} else if("initHotelSelct".equals(op)) {
			// 初始化房间类型选择框的方法
			doInitHotelSelct(request, response);
		} else if("initRoomTypeSelct".equals(op)) {
			// 初始化房间类型选择框的方法
			doInitRoomTypeSelct(request, response);
		} else if("insertRoom".equals(op)) {
			// 初始化房间类型选择框的方法
			doInsertRoom(request, response);
		} else if("searchRoomsByHotelId".equals(op)) {
			// 初始化房间类型选择框的方法
			try {
				doSearchRoomsByHotelId(request, response);
			} catch (NumberFormatException | SQLException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 根据hotelId查询该酒店下的所有房间
	 * @param request
	 * @param response
	 * @throws SQLException 
	 * @throws NumberFormatException 
	 * @throws IOException 
	 */
	private void doSearchRoomsByHotelId(HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, SQLException, IOException {
		
		String hotelId = request.getParameter("hotelId");
		if (hotelId == null) {
			return;
		}
		
		List<Room> list = roomService.queryRoomsByHotelId(Integer.parseInt(hotelId));
		
		// 封装数据
	    ObjectMapper objectMapper = new ObjectMapper();
	    String json = objectMapper.writeValueAsString(list);
	    // 设置响应内容类型
	    response.setContentType("application/json;charset=utf-8");
	    // 响应数据
	    PrintWriter out= response.getWriter();
	    out.print(json);
		
	}

	private void doInsertRoom(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		String hotelId = request.getParameter("hotelId");
		String roomTypeId = request.getParameter("roomTypeId");
		System.out.println("hotelId" + hotelId);
		System.out.println("roomTypeId" + roomTypeId);
		
		String roomName = request.getParameter("roomName");
		String roomPrice = request.getParameter("roomPrice");
		
		// 获取单个文件
		Part part = request.getPart("roomPicture");
	
		// 判断用户是否有上传文件
		if (part.getSize() == 0) {
			// 调用业务层 编辑room
			Room room = new Room(null, Integer.parseInt(hotelId),Integer.parseInt(roomTypeId), new BigDecimal(roomPrice), roomName, null);
			boolean modify = roomService.getInsertRoom(room);
			if (modify) {
			    // 响应数据
			    PrintWriter out= response.getWriter();
			    out.print("success");
			}
			
		} else {
			System.out.println("有上传的图片");
			// 有上传酒店的图片
			// 对上传的文件类型进行效验
			String allowImgType = "image/jpg,image/jpeg,image/png,image/gif";
			// 获取当前文件的内容类型
			String contentType = part.getContentType();
			if (allowImgType.indexOf(contentType) == -1) {
				// 文件类型不匹配
				System.out.println("上传文件类型不匹配");
				// 重定向注册页面,提示文件格式错误
	//			response.sendRedirect("front/register.jsp?fileuploaderror=notallowtype");
				return;
			}else {
				// 获取上传的真实文件名
				String realFileName = part.getSubmittedFileName();
				// 保证文件名唯一
				// 时间戳
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
				String time = formatter.format(now);
				// 4位随机数
				int random = (int)((Math.random()*9+1)*1000);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(time).append(random).append(realFileName);
				
				// 定义文件存储目录
				File file = new File("D:\\image\\hotel");
				
				StringBuffer filePath = new StringBuffer();
				
				filePath.append(file.getPath()).append(File.separator).append(fileName);
				
				// 将文件写入指定位置
				part.write(filePath.toString());
				
				// 调用业务逻辑层
				Room room = new Room(null, Integer.parseInt(hotelId),Integer.parseInt(roomTypeId), new BigDecimal(roomPrice), roomName, fileName.toString());

				System.out.println("上传的fileName文件名为" + fileName.toString());
				boolean modify = roomService.getInsertRoom(room);
				
				if (modify) {
					System.out.println("修改带roomPicture成功");
				}
				
				response.sendRedirect("back/room-management.jsp");
				}
			}		
		
	}

	private void doInitRoomTypeSelct(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		List<RoomType> list = new RoomTypeServiceImpl().queryAllRoomTypes();
		
		list.forEach(System.out::println);
		
		// 封装数据
	    ObjectMapper objectMapper = new ObjectMapper();
	    String json = objectMapper.writeValueAsString(list);
	    // 设置响应内容类型
	    response.setContentType("application/json;charset=utf-8");
	    // 响应数据
	    PrintWriter out= response.getWriter();
	    out.print(json);
		
		
	}
	
	/**
	 * 初始化新增客房，酒店选择框内容的方法
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void doInitHotelSelct(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		List<Hotel> list = new HotelServiceImpl().queryAllHotels();
		System.out.println("执行了doInitHotelServlet方法");
		list.forEach(System.out::println);
		
		// 封装数据
	    ObjectMapper objectMapper = new ObjectMapper();
	    String json = objectMapper.writeValueAsString(list);
	    // 设置响应内容类型
	    response.setContentType("application/json;charset=utf-8");
	    // 响应数据
	    PrintWriter out= response.getWriter();
	    out.print(json);
		
		
	}


	
	private void doSearchRoomByPageAndName(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
		
		int pageNum = Integer.parseInt(request.getParameter("pageNum"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		String hotelName = request.getParameter("keyword");
		
		if (hotelName==null) {
			hotelName="";
		}
		
		PageInfo<Room> pageInfo = roomService.queryRoomByPageAndName(pageNum, pageSize, hotelName);
		// 封装数据
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(pageInfo);
		System.out.println(json);
		// 设置响应内容类型
		response.setContentType("application/json;charset=utf-8");
		// 响应数据
		PrintWriter  out= response.getWriter();
		out.print(json);
	}
	
	private void doDeleteRoomById(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {

		// 调用业务层
		String roomId = request.getParameter("roomId");

		if (roomId == null) {
			return;
		}
		
		roomService.deleteRoomByIdSuccessOrNot(Integer.parseInt(roomId));
		// 再次一次查询分页结果
		int pageNum = Integer.parseInt(request.getParameter("pageNum"));
		int pageSize = Integer.parseInt(request.getParameter("pageSize"));
		String hotelName = request.getParameter("keyword");
		PageInfo<Room> pageInfo = roomService.queryRoomByPageAndName(pageNum, pageSize, hotelName);
		// 封装数据
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writeValueAsString(pageInfo);
		System.out.println(json);
		// 设置响应内容类型
		response.setContentType("application/json;charset=utf-8");
		// 响应数据
		PrintWriter out= response.getWriter();
		out.print(json);
		
	}
	

	private void doGetRoomById(HttpServletRequest request, HttpServletResponse response) throws IOException, NumberFormatException, SQLException {
		
		String roomId = request.getParameter("roomId");
		if (roomId == null) {
			return;
		}
		
		List<Room> list = roomService.getRoomById(Integer.parseInt(roomId));
		
		// 封装数据
	    ObjectMapper objectMapper = new ObjectMapper();
	    String json = objectMapper.writeValueAsString(list);
	    // 设置响应内容类型
	    response.setContentType("application/json;charset=utf-8");
	    // 响应数据
	    PrintWriter out= response.getWriter();
	    out.print(json);
		
		
	}

	
	private void doModify(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		
		// 获取普通组件
		String roomId = request.getParameter("modal-roomId");

		String roomTypeId = request.getParameter("modal-roomType");
		
		String roomName = request.getParameter("modal-roomName");
		String roomPrice = request.getParameter("modal-roomPrice");
		
		// 获取单个文件
		Part part = request.getPart("modify-room-picture");
		
		// 判断用户是否有上传文件
		if (part.getSize() == 0) {
			
			
			Room room = new Room(Integer.parseInt(roomId), null , Integer.parseInt(roomTypeId), new BigDecimal(roomPrice), roomName, null);
			boolean modify = roomService.modifyRoomWithNoPictureSuccessOrNot(room);
			
			if (modify) {
			    // 响应数据
			    PrintWriter  out= response.getWriter();
			    out.print("success");
			    response.sendRedirect("back/room-management.jsp");
			}
			System.out.println("用户有上传文件");
		} else {
			System.out.println("有上传的图片");
			// 有上传酒店的图片
			// 对上传的文件类型进行效验
			String allowImgType = "image/jpg,image/jpeg,image/png,image/gif";
			// 获取当前文件的内容类型
			String contentType = part.getContentType();
			if (allowImgType.indexOf(contentType) == -1) {
				// 文件类型不匹配
				System.out.println("上传文件类型不匹配");
				// 重定向注册页面,提示文件格式错误
//					response.sendRedirect("front/register.jsp?fileuploaderror=notallowtype");
				return;
			}else {
				// 获取上传的真实文件名
				String realFileName = part.getSubmittedFileName();
				// 保证文件名唯一
				// 时间戳
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
				String time = formatter.format(now);
				// 4位随机数
				int random = (int)((Math.random()*9+1)*1000);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(time).append(random).append(realFileName);
				
				// 定义文件存储目录
				File file = new File("D:\\image\\hotel");
				
				StringBuffer filePath = new StringBuffer();
				
				filePath.append(file.getPath()).append(File.separator).append(fileName);
				
				// 将文件写入指定位置
				part.write(filePath.toString());
				
				// 调用业务逻辑层
				Room room = new Room(Integer.parseInt(roomId), null , Integer.parseInt(roomTypeId), new BigDecimal(roomPrice), roomName, fileName.toString());
				System.out.println("带文件修改的用来传参的Room实体类" + room);
				System.out.println("上传的fileName文件名为" + fileName.toString());
				
				roomService.modifyRoomWithPictureSuccessOrNot(room);

				
				System.out.println("修改带roomPicture成功");
				response.sendRedirect("back/room-management.jsp");
				}
			}
	}
	

	/**
	 * 初始化房间类型选择框的方法
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void doInitSelect(HttpServletRequest request, HttpServletResponse response) throws IOException {

		List<RoomType> list = new RoomTypeServiceImpl().queryAllRoomTypes();
		
		// 封装数据
	    ObjectMapper objectMapper = new ObjectMapper();
	    String json = objectMapper.writeValueAsString(list);
	    // 设置响应内容类型
	    response.setContentType("application/json;charset=utf-8");
	    // 响应数据
	    PrintWriter out= response.getWriter();
	    out.print(json);
		
	}
	
	
	
	


}
